package [basepackage].config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
@MapperScan(basePackages = "[basepackage].dao", sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class PrimaryDatasourceConf {

	/*
	 * micro模块已封装数据源的获取,设置第二数据源需要配置
	 * 
	 * @Bean("primaryDatasource")
	 * 
	 * @Primary
	 * 
	 * @ConfigurationProperties(prefix = "common.micro.spring.datasource") public
	 * javax.sql.DataSource oldcoreDataSource() { return
	 * DataSourceBuilder.create().type(DruidDataSource.class).build(); }
	 */

	@Bean(name = "primarySqlSessionFactory")
	@Primary
	public SqlSessionFactory rdsSqlSessionFactory(
			@Qualifier("primaryDatasource") javax.sql.DataSource primaryDataSource) throws Exception {
		final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(primaryDataSource);
		sessionFactory.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/primary/sqlmap/*.xml"));
		sessionFactory.setConfigLocation(
				new PathMatchingResourcePatternResolver().getResource("classpath:mybatis/primary/sqlmap-config.xml"));
		return sessionFactory.getObject();
	}

	@Bean(name = "primarySqlSessionTemplate")
	@Primary
	public SqlSessionTemplate testSqlSessionTemplate(
			@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

	@Primary
	@Bean(name = "primaryJdbcTemplate")
	public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDatasource") DataSource dataSource) {
		return new JdbcTemplate(dataSource);
	}
}
